package com.appinfo.aspect;

import com.appinfo.annotation.AvoidRepeatableCommit;
import com.appinfo.redis.RedisService;
import com.appinfo.redis.SubTokenKey;
import com.appinfo.utils.IPUtil;
import com.appinfo.utils.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;


import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
@Slf4j
public class AvoidRepeatableCommitAspect {
    @Autowired
    private RedisService redisService;

    @Around("@annotation(com.appinfo.annotation.AvoidRepeatableCommit)")
    public Object around(ProceedingJoinPoint point) throws Throwable{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String ip = IPUtil.getIP(request);
        //获取方法名与类名
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        String className = method.getDeclaringClass().getName();
        String name = method.getName();
        String ipKey = String.format("%s#%s", className, name);
        int hashCode = Math.abs(ipKey.hashCode());
        String key = String.format("%s#%s", ip, hashCode);
        log.info("ipKey={},hashCode={},key={}",ipKey,hashCode,key);
        AvoidRepeatableCommit avoidRepeatableCommit = method.getAnnotation(AvoidRepeatableCommit.class);
        long timeout = avoidRepeatableCommit.timeout();
        if(timeout < 0){
            timeout = 10;
        }
        String value = redisService.get(SubTokenKey.subToken,ipKey,String.class);
        if(StringUtils.isNotBlank(value)){
            request.setAttribute("msg","请勿重复提交,请点击<a href='/dev/flatform/app/appinfoadd'>返回</a>");
            return "请勿重复提交！";
        }
        redisService.set(SubTokenKey.getKey((int)timeout),ipKey, UUIDUtil.uuid());
        Object object = point.proceed();
        return object;
    }
}
